home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2008 February / PCWFEB08.iso / Software / Resources / Developers / XAMPP 1.5.4 / Windows installer / xampp-win32-1.5.4-installer.exe / xampp / php / pear / Console / Getargs.php next >
Encoding:
PHP Script  |  2005-12-02  |  41.1 KB  |  1,062 lines

  1. <?php
  2. /* vim: set expandtab tabstop=4 shiftwidth=4: */
  3. // +----------------------------------------------------------------------+
  4. // | PHP Version 4                                                        |
  5. // +----------------------------------------------------------------------+
  6. // | Copyright (c) 2004 The PHP Group                                     |
  7. // +----------------------------------------------------------------------+
  8. // | This source file is subject to version 3.0 of the PHP license,       |
  9. // | that is bundled with this package in the file LICENSE, and is        |
  10. // | available through the world-wide-web at the following url:           |
  11. // | http://www.php.net/license/3_0.txt.                                  |
  12. // | If you did not receive a copy of the PHP license and are unable to   |
  13. // | obtain it through the world-wide-web, please send a note to          |
  14. // | license@php.net so we can mail you a copy immediately.               |
  15. // +----------------------------------------------------------------------+
  16. // | Author: Bertrand Mansion <bmansion@mamasam.com>                      |
  17. // +----------------------------------------------------------------------+
  18. //
  19. // $Id: Getargs.php,v 1.17 2005/04/08 07:11:37 wenz Exp $
  20.  
  21. require_once 'PEAR.php';
  22.  
  23. /**#@+
  24.  * Error Constants
  25.  */
  26. /**
  27.  * Wrong configuration
  28.  *
  29.  * This error will be TRIGGERed when a configuration error is found, 
  30.  * it will also issue a WARNING.
  31.  */
  32. define('CONSOLE_GETARGS_ERROR_CONFIG', -1);
  33.  
  34. /**
  35.  * User made an error
  36.  *
  37.  * This error will be RETURNed when a bad parameter 
  38.  * is found in the command line, for example an unknown parameter
  39.  * or a parameter with an invalid number of options.
  40.  */
  41. define('CONSOLE_GETARGS_ERROR_USER', -2);
  42.  
  43. /**
  44.  * Help text wanted
  45.  *
  46.  * This error will be RETURNed when the user asked to 
  47.  * see the help by using <kbd>-h</kbd> or <kbd>--help</kbd> in the command line, you can then print
  48.  * the help ascii art text by using the {@link Console_Getargs::getHelp()} method
  49.  */
  50. define('CONSOLE_GETARGS_HELP', -3);
  51.  
  52. /**
  53.  * Option name for application "parameters"
  54.  *
  55.  * Parameters are the options an application needs to function.
  56.  * The two files passed to the diff command would be considered
  57.  * the parameters. These are different from other options in that
  58.  * they do not need an option name passed on the command line.
  59.  */
  60. define('CONSOLE_GETARGS_PARAMS', 'parameters');
  61. /**#@-*/
  62.  
  63. /**
  64.  * Command-line arguments parsing class
  65.  * 
  66.  * This implementation was freely inspired by a python module called
  67.  * getargs by Vinod Vijayarajan and a perl CPAN module called
  68.  * Getopt::Simple by Ron Savage
  69.  *
  70.  * This class implements a Command Line Parser that your cli applications
  71.  * can use to parse command line arguments found in $_SERVER['argv'] or a
  72.  * user defined array.
  73.  * 
  74.  * It gives more flexibility and error checking than Console_Getopt. It also
  75.  * performs some arguments validation and is capable to return a formatted
  76.  * help text to the user, based on the configuration it is given.
  77.  * 
  78.  * The class provides the following capabilities:
  79.  * - Each command line option can take an arbitrary number of arguments.
  80.  * - Makes the distinction between switches (options without arguments) 
  81.  *   and options that require arguments.
  82.  * - Recognizes 'single-argument-options' and 'default-if-set' options.
  83.  * - Switches and options with arguments can be interleaved in the command
  84.  *   line.
  85.  * - You can specify the maximum and minimum number of arguments an option
  86.  *   can take. Use -1 if you don't want to specify an upper bound.
  87.  * - Specify the default arguments to an option
  88.  * - Short options can be more than one letter in length.
  89.  * - A given option may be invoked by multiple names (aliases).
  90.  * - Understands by default the --help, -h options
  91.  * - Can return a formatted help text
  92.  * - Arguments may be specified using the '=' syntax also.
  93.  * - Short option names may be concatenated (-dvw 100 == -d -v -w 100)
  94.  * - Can define a default option that will take any arguments added without
  95.  *   an option name
  96.  * - Can pass in a user defined array of arguments instead of using
  97.  *   $_SERVER['argv']
  98.  * 
  99.  * @todo      Implement the parsing of comma delimited arguments
  100.  * @todo      Implement method for turning assocative arrays into command
  101.  *            line arguments (ex. array('d' => true, 'v' => 2) -->
  102.  *                                array('-d', '-v', 2))
  103.  *
  104.  * @author    Bertrand Mansion <bmansion@mamasam.com>
  105.  * @copyright 2004
  106.  * @license   http://www.php.net/license/3_0.txt PHP License 3.0
  107.  * @version   @VER@
  108.  * @package   Console_Getargs
  109.  */
  110. class Console_Getargs
  111. {
  112.     /**
  113.      * Factory creates a new {@link Console_Getargs_Options} object
  114.      *
  115.      * This method will return a new {@link Console_Getargs_Options}
  116.      * built using the given configuration options. If the configuration
  117.      * or the command line options contain errors, the returned object will 
  118.      * in fact be a PEAR_Error explaining the cause of the error.
  119.      *
  120.      * Factory expects an array as parameter.
  121.      * The format for this array is:
  122.      * <pre>
  123.      * array(
  124.      *  longname => array('short'   => Short option name,
  125.      *                    'max'     => Maximum arguments for option,
  126.      *                    'min'     => Minimum arguments for option,
  127.      *                    'default' => Default option argument,
  128.      *                    'desc'    => Option description)
  129.      * )
  130.      * </pre>
  131.      * 
  132.      * If an option can be invoked by more than one name, they have to be defined
  133.      * by using | as a separator. For example: name1|name2
  134.      * This works both in long and short names.
  135.      *
  136.      * max/min are the most/least number of arguments an option accepts.
  137.      *
  138.      * The 'defaults' field is optional and is used to specify default
  139.      * arguments to an option. These will be assigned to the option if 
  140.      * it is *not* used in the command line.
  141.      * Default arguments can be:
  142.      * - a single value for options that require a single argument,
  143.      * - an array of values for options with more than one possible arguments.
  144.      * Default argument(s) are mandatory for 'default-if-set' options.
  145.      *
  146.      * If max is 0 (option is just a switch), min is ignored.
  147.      * If max is -1, then the option can have an unlimited number of arguments 
  148.      * greater or equal to min.
  149.      * 
  150.      * If max == min == 1, the option is treated as a single argument option.
  151.      * 
  152.      * If max >= 1 and min == 0, the option is treated as a
  153.      * 'default-if-set' option. This implies that it will get the default argument
  154.      * only if the option is used in the command line without any value.
  155.      * (Note: defaults *must* be specified for 'default-if-set' options) 
  156.      *
  157.      * If the option is not in the command line, the defaults are 
  158.      * *not* applied. If an argument for the option is specified on the command
  159.      * line, then the given argument is assigned to the option.
  160.      * Thus:
  161.      * - a --debug in the command line would cause debug = 'default argument'
  162.      * - a --debug 2 in the command line would result in debug = 2
  163.      *  if not used in the command line, debug will not be defined.
  164.      * 
  165.      * Example 1.
  166.      * <code>
  167.      * require_once 'Console_Getargs.php';
  168.      *
  169.      * $args =& Console_Getargs::factory($config);
  170.      * 
  171.      * if (PEAR::isError($args)) {
  172.      *  if ($args->getCode() === CONSOLE_GETARGS_ERROR_USER) {
  173.      *    echo Console_Getargs::getHelp($config, null, $args->getMessage())."\n";
  174.      *  } else if ($args->getCode() === CONSOLE_GETARGS_HELP) {
  175.      *    echo Console_Getargs::getHelp($config)."\n";
  176.      *  }
  177.      *  exit;
  178.      * }
  179.      * 
  180.      * echo 'Verbose: '.$args->getValue('verbose')."\n";
  181.      * if ($args->isDefined('bs')) {
  182.      *  echo 'Block-size: '.(is_array($args->getValue('bs')) ? implode(', ', $args->getValue('bs'))."\n" : $args->getValue('bs')."\n");
  183.      * } else {
  184.      *  echo "Block-size: undefined\n";
  185.      * }
  186.      * echo 'Files: '.($args->isDefined('file') ? implode(', ', $args->getValue('file'))."\n" : "undefined\n");
  187.      * if ($args->isDefined('n')) {
  188.      *  echo 'Nodes: '.(is_array($args->getValue('n')) ? implode(', ', $args->getValue('n'))."\n" : $args->getValue('n')."\n");
  189.      * } else {
  190.      *  echo "Nodes: undefined\n";
  191.      * }
  192.      * echo 'Log: '.$args->getValue('log')."\n";
  193.      * echo 'Debug: '.($args->isDefined('d') ? "YES\n" : "NO\n");
  194.      * 
  195.      * </code>
  196.      *
  197.      * If you don't want to require any option name for a set of arguments,
  198.      * or if you would like any "leftover" arguments assigned by default, 
  199.      * you can create an option named CONSOLE_GETARGS_PARAMS that will
  200.      * grab any arguments that cannot be assigned to another option. The
  201.      * rules for CONSOLE_GETARGS_PARAMS are still the same. If you specify
  202.      * that two values must be passed then two values must be passed. See
  203.      * the example script for a complete example.
  204.      * 
  205.      * @param  array  $config     associative array with keys being the
  206.      *                            options long name
  207.      * @param  array  $arguments  numeric array of command line arguments
  208.      * @access public
  209.      * @return object|PEAR_Error  a newly created Console_Getargs_Options
  210.      *                            object or a PEAR_Error object on error
  211.      */
  212.     function &factory($config = array(), $arguments = NULL)
  213.     {
  214.         // Create the options object.
  215.         $obj =& new Console_Getargs_Options();
  216.         
  217.         // Try to set up the arguments.
  218.         $err = $obj->init($config, $arguments);
  219.         if ($err !== true) {
  220.             return $err;
  221.         }
  222.         
  223.         // Try to set up the options.
  224.         $err = $obj->buildMaps();
  225.         if ($err !== true) {
  226.             return $err;
  227.         }
  228.         
  229.         // Get the options and arguments from the command line.
  230.         $err = $obj->parseArgs();
  231.         if ($err !== true) {
  232.             return $err;
  233.         }
  234.         
  235.         // Set arguments for options that have defaults.
  236.         $err = $obj->setDefaults();
  237.         if ($err !== true) {
  238.             return $err;
  239.         }
  240.         
  241.         // All is good.
  242.         return $obj;
  243.     }
  244.     
  245.     /**
  246.      * Returns an ascii art version of the help
  247.      *
  248.      * This method uses the given configuration and parameters
  249.      * to create and format an help text for the options you defined
  250.      * in your config parameter. You can supply a header and a footer
  251.      * as well as the maximum length of a line. If you supplied
  252.      * descriptions for your options, they will be used as well.
  253.      *
  254.      * By default, it returns something like this:
  255.      * <pre>
  256.      * Usage: myscript.php [-dv --formats] <-fw --filters>
  257.      * 
  258.      * -f --files values(2)          Set the source and destination image files.
  259.      * -w --width=<value>      Set the new width of the image.
  260.      * -d --debug                    Switch to debug mode.
  261.      * --formats values(1-3)         Set the image destination format. (jpegbig,
  262.      *                               jpegsmall)
  263.      * -fi --filters values(1-...)   Set the filters to be applied to the image upon
  264.      *                               conversion. The filters will be used in the order
  265.      *                               they are set.
  266.      * -v --verbose (optional)value  Set the verbose level. (3)
  267.      * </pre>
  268.      *
  269.      * @access public
  270.      * @param  array  your args configuration
  271.      * @param  string the header for the help. If it is left null,
  272.      *                a default header will be used, starting by Usage:
  273.      * @param  string the footer for the help. This could be used
  274.      *                to supply a description of the error the user made
  275.      * @param  int    help lines max length
  276.      * @return string the formatted help text
  277.      */
  278.     function getHelp($config, $helpHeader = null, $helpFooter = '', $maxlength = 78)
  279.     {
  280.         // Start with an empty help message and build it piece by piece
  281.         $help = '';
  282.         
  283.         // If no user defined header, build the default header.
  284.         if (!isset($helpHeader)) {
  285.             // Get the optional, required and "paramter" names for this config.
  286.             list($optional, $required, $params) = Console_Getargs::getOptionalRequired($config);
  287.             // Start with the file name.
  288.             $helpHeader = 'Usage: '. basename($_SERVER['SCRIPT_NAME']) . ' ';
  289.             // Add the optional arguments and required arguments.
  290.             $helpHeader.= $optional . ' ' . $required . ' ';
  291.             // Add any parameters that are needed.
  292.             $helpHeader.= $params . "\n\n";
  293.         }
  294.         
  295.         // Build the list of options and definitions.
  296.         $i = 0;
  297.         foreach ($config as $long => $def) {
  298.             
  299.             // Break the names up if there is more than one for an option.
  300.             $shortArr = array();
  301.             if (isset($def['short'])) {
  302.                 $shortArr = explode('|', $def['short']);
  303.             }
  304.             $longArr = explode('|', $long);
  305.             
  306.             // Column one is the option name displayed as "-short, --long [additional info]"
  307.             // Add the short option name.
  308.             $col1[$i] = !empty($shortArr) ? '-'.$shortArr[0].' ' : '';
  309.             // Add the long option name.
  310.             $col1[$i] .= '--'.$longArr[0];
  311.             
  312.             // Get the min and max to show needed/optional values.
  313.             $max = $def['max'];
  314.             $min = isset($def['min']) ? $def['min'] : $max;
  315.             
  316.             if ($max === 1 && $min === 1) {
  317.                 // One value required.
  318.                 $col1[$i] .= '=<value>';
  319.             } else if ($max > 1) {
  320.                 if ($min === $max) {
  321.                     // More than one value needed.
  322.                     $col1[$i] .= ' values('.$max.')';
  323.                 } else if ($min === 0) {
  324.                     // Argument takes optional value(s).
  325.                     $col1[$i] .= ' values(optional)';
  326.                 } else {
  327.                     // Argument takes a range of values.
  328.                     $col1[$i] .= ' values('.$min.'-'.$max.')';
  329.                 }
  330.             } else if ($max === 1 && $min === 0) {
  331.                 // Argument can take at most one value.
  332.                 $col1[$i] .= ' (optional)value';
  333.             } else if ($max === -1) {
  334.                 // Argument can take unlimited values.
  335.                 if ($min > 0) {
  336.                     $col1[$i] .= ' values('.$min.'-...)';
  337.                 } else {
  338.                     $col1[$i] .= ' (optional)values';
  339.                 }
  340.             }
  341.             
  342.             // Column two is the description if available.
  343.             if (isset($def['desc'])) {
  344.                 $col2[$i] = $def['desc'];
  345.             } else {
  346.                 $col2[$i] = '';
  347.             }
  348.             // Add the default value(s) if there are any/
  349.             if (isset($def['default'])) {
  350.                 if (is_array($def['default'])) {
  351.                     $col2[$i] .= ' ('.implode(', ', $def['default']).')';
  352.                 } else {
  353.                     $col2[$i] .= ' ('.$def['default'].')';
  354.                 }
  355.             }
  356.             $i++;
  357.         }
  358.         
  359.         // Figure out the maximum length for column one.
  360.         $arglen = 0;
  361.         foreach ($col1 as $txt) {
  362.             $length = strlen($txt);
  363.             if ($length > $arglen) {
  364.                 $arglen = $length;
  365.             }
  366.         }
  367.         
  368.         // The maximum length for each description line.
  369.         $desclen = $maxlength - $arglen;
  370.         $padding = str_repeat(' ', $arglen);
  371.         foreach ($col1 as $k => $txt) {
  372.             // Wrap the descriptions.
  373.             if (strlen($col2[$k]) > $desclen) {
  374.                 $desc = wordwrap($col2[$k], $desclen, "\n  ".$padding);
  375.             } else {
  376.                 $desc = $col2[$k];
  377.             }
  378.             // Push everything together.
  379.             $help .= str_pad($txt, $arglen).'  '.$desc."\n";
  380.         }
  381.         
  382.         // Put it all together.
  383.         return $helpHeader.$help.$helpFooter;
  384.     }
  385.     
  386.     /**
  387.      * Parse the config array to determine which flags are
  388.      * optional and which are required.
  389.      *
  390.      * To make the help header more descriptive, the options
  391.      * are shown seperated into optional and required flags.
  392.      * When possible the short flag is used for readability.
  393.      * Optional items (including "parameters") are surrounded
  394.      * in square braces ([-vd]). Required flags are surrounded
  395.      * in angle brackets (<-wf>). 
  396.      *
  397.      * This method may be called statically.
  398.      *
  399.      * @access  public
  400.      * @param   &$config The config array.
  401.      * @return  array
  402.      * @author  Scott Mattocks
  403.      * @package Console_Getargs
  404.      */
  405.     function getOptionalRequired(&$config)
  406.     {
  407.         // Parse the config array and look for optional/required
  408.         // tags.
  409.         $optional         = '';
  410.         $optionalHasShort = false;
  411.         $required         = '';
  412.         $requiredHasShort = false;
  413.         
  414.         ksort($config);
  415.         foreach ($config as $long => $def) {
  416.             
  417.             // We only really care about the first option name.
  418.             $long = reset(explode('|', $long));
  419.             
  420.             // Treat the "parameters" specially.
  421.             if ($long == CONSOLE_GETARGS_PARAMS) {
  422.                 continue;
  423.             }
  424.             // We only really care about the first option name.
  425.             $def['short'] = reset(explode('|', $def['short']));
  426.             
  427.             if (!isset($def['min']) || $def['min'] == 0 || isset($def['default'])) {
  428.                 // This argument is optional.
  429.                 if (isset($def['short']) && strlen($def['short']) == 1) {
  430.                     $optional         = $def['short'] . $optional;
  431.                     $optionalHasShort = true;
  432.                 } else {
  433.                     $optional.= ' --' . $long;
  434.                 }
  435.             } else {
  436.                 // This argument is required.
  437.                 if (isset($def['short']) && strlen($def['short']) == 1) {
  438.                     $required         = $def['short'] . $required;
  439.                     $requiredHasShort = true;
  440.                 } else {
  441.                     $required.= ' --' . $long;
  442.                 }
  443.             }
  444.         }
  445.         
  446.         // Check for "parameters" option.
  447.         $params = '';
  448.         if (isset($config[CONSOLE_GETARGS_PARAMS])) {
  449.             for ($i = 1; $i <= max($config[CONSOLE_GETARGS_PARAMS]['max'], $config[CONSOLE_GETARGS_PARAMS]['min']); ++$i) {
  450.                 if ($config[CONSOLE_GETARGS_PARAMS]['max'] == -1 ||
  451.                     ($i > $config[CONSOLE_GETARGS_PARAMS]['min'] &&
  452.                      $i <= $config[CONSOLE_GETARGS_PARAMS]['max']) ||
  453.                     isset($config[CONSOLE_GETARGS_PARAMS]['default'])) {
  454.                     // Parameter is optional.
  455.                     $params.= '[param' . $i .'] ';
  456.                 } else {
  457.                     // Parameter is required.
  458.                     $params.= 'param' . $i . ' ';
  459.                 }
  460.             }
  461.         }
  462.         // Add a leading - if needed.
  463.         if ($optionalHasShort) {
  464.             $optional = '-' . $optional;
  465.         }
  466.         
  467.         if ($requiredHasShort) {
  468.             $required = '-' . $required;
  469.         }
  470.         
  471.         // Add the extra characters if needed.
  472.         if (!empty($optional)) {
  473.             $optional = '[' . $optional . ']';
  474.         }
  475.         if (!empty($required)) {
  476.             $required = '<' . $required . '>';
  477.         }
  478.         
  479.         return array($optional, $required, $params);
  480.     }
  481. } // end class Console_Getargs
  482.  
  483. /**
  484.  * This class implements a wrapper to the command line options and arguments.
  485.  *
  486.  * @author Bertrand Mansion <bmansion@mamasam.com>
  487.  * @package  Console_Getargs
  488.  */
  489. class Console_Getargs_Options
  490. {
  491.     
  492.     /**
  493.      * Lookup to match short options name with long ones
  494.      * @var array
  495.      * @access private
  496.      */
  497.     var $_shortLong = array();
  498.     
  499.     /**
  500.      * Lookup to match alias options name with long ones
  501.      * @var array
  502.      * @access private
  503.      */
  504.     var $_aliasLong = array();
  505.     
  506.     /**
  507.      * Arguments set for the options
  508.      * @var array
  509.      * @access private
  510.      */
  511.     var $_longLong = array();
  512.     
  513.     /**
  514.      * Configuration set at initialization time
  515.      * @var array
  516.      * @access private
  517.      */
  518.     var $_config = array();
  519.     
  520.     /**
  521.      * A read/write copy of argv
  522.      * @var array
  523.      * @access private
  524.      */
  525.     var $args = array();
  526.     
  527.     /**
  528.      * Initializes the Console_Getargs_Options object
  529.      * @param array configuration options
  530.      * @access private
  531.      * @throws CONSOLE_GETARGS_ERROR_CONFIG
  532.      * @return true|PEAR_Error
  533.      */
  534.     function init($config, $arguments = NULL)
  535.     {
  536.         if (is_array($arguments)) {
  537.             // Use the user defined argument list.
  538.             $this->args = $arguments;
  539.         } else {
  540.             // Command line arguments must be available.
  541.             if (!isset($_SERVER['argv']) || !is_array($_SERVER['argv'])) {
  542.                 return PEAR::raiseError("Could not read argv", CONSOLE_GETARGS_ERROR_CONFIG,
  543.                                         PEAR_ERROR_TRIGGER, E_USER_WARNING, 'Console_Getargs_Options::init()');
  544.             }
  545.             $this->args = $_SERVER['argv'];
  546.         }
  547.         
  548.         // Drop the first argument if it doesn't begin with a '-'.
  549.         if (isset($this->args[0]{0}) && $this->args[0]{0} != '-') {
  550.             array_shift($this->args);
  551.         }
  552.         $this->_config = $config;
  553.         return true;
  554.     }
  555.     
  556.     /**
  557.      * Makes the lookup arrays for alias and short name mapping with long names
  558.      * @access private
  559.      * @throws CONSOLE_GETARGS_ERROR_CONFIG
  560.      * @return true|PEAR_Error
  561.      */
  562.     function buildMaps()
  563.     {
  564.         foreach($this->_config as $long => $def) {
  565.             
  566.             $longArr = explode('|', $long);
  567.             $longname = $longArr[0];
  568.             
  569.             if (count($longArr) > 1) {
  570.                 // The fisrt item in the list is "the option".
  571.                 // The rest are aliases.
  572.                 array_shift($longArr);
  573.                 foreach($longArr as $alias) {
  574.                     // Watch out for duplicate aliases.
  575.                     if (isset($this->_aliasLong[$alias])) {
  576.                         return PEAR::raiseError('Duplicate alias for long option '.$alias, CONSOLE_GETARGS_ERROR_CONFIG,
  577.                                                 PEAR_ERROR_TRIGGER, E_USER_WARNING, 'Console_Getargs_Options::buildMaps()');
  578.                         
  579.                     }
  580.                     $this->_aliasLong[$alias] = $longname;
  581.                 }
  582.                 // Add the real option name and defintion.
  583.                 $this->_config[$longname] = $def;
  584.                 // Get rid of the old version (name|alias1|...)
  585.                 unset($this->_config[$long]);
  586.             }
  587.             
  588.             // Add the (optional) short option names.
  589.             if (!empty($def['short'])) {
  590.                 // Short names
  591.                 $shortArr = explode('|', $def['short']);
  592.                 $short = $shortArr[0];
  593.                 if (count($shortArr) > 1) {
  594.                     // The first item is "the option".
  595.                     // The rest are aliases.
  596.                     array_shift($shortArr);
  597.                     foreach ($shortArr as $alias) {
  598.                         // Watch out for duplicate aliases.
  599.                         if (isset($this->_shortLong[$alias])) {
  600.                             return PEAR::raiseError('Duplicate alias for short option '.$alias, CONSOLE_GETARGS_ERROR_CONFIG,
  601.                                                     PEAR_ERROR_TRIGGER, E_USER_WARNING, 'Console_Getargs_Options::buildMaps()');
  602.                         }
  603.                         $this->_shortLong[$alias] = $longname;
  604.                     }
  605.                 }
  606.                 // Add the real short option name.
  607.                 $this->_shortLong[$short] = $longname;
  608.             }
  609.         }
  610.         return true;
  611.     }
  612.     
  613.     /**
  614.      * Parses the given options/arguments one by one
  615.      * @access private
  616.      * @throws CONSOLE_GETARGS_HELP
  617.      * @throws CONSOLE_GETARGS_ERROR_USER
  618.      * @return true|PEAR_Error
  619.      */
  620.     function parseArgs()
  621.     {
  622.         // Go through the options and parse the arguments for each.
  623.         for ($i = 0, $count = count($this->args); $i < $count; $i++) {
  624.             $arg = $this->args[$i];
  625.             if ($arg === '--help' || $arg === '-h') {
  626.                 // Asking for help breaks the loop.
  627.                 return PEAR::raiseError(null, CONSOLE_GETARGS_HELP, PEAR_ERROR_RETURN);
  628.  
  629.             }
  630.             if ($arg === '--') {
  631.                 // '--' alone signals the start of "parameters"
  632.                 $err = $this->parseArg(CONSOLE_GETARGS_PARAMS, true, ++$i);
  633.             } elseif (strlen($arg) > 1 && $arg{0} == '-' && $arg{1} == '-') {
  634.                 // Long name used (--option)
  635.                 $err = $this->parseArg(substr($arg, 2), true, $i);
  636.             } else if (strlen($arg) > 1 && $arg{0} == '-') {
  637.                 // Short name used (-o)
  638.                 $err = $this->parseArg(substr($arg, 1), false, $i);
  639.                 if ($err === -1) {
  640.                     break;
  641.                 }
  642.             } elseif (isset($this->_config[CONSOLE_GETARGS_PARAMS])) {
  643.                 // No flags at all. Try the parameters option.
  644.                 $tempI = &$i - 1;
  645.                 $err = $this->parseArg(CONSOLE_GETARGS_PARAMS, true, $tempI);
  646.             } else {
  647.                 $err = PEAR::raiseError('Unknown argument '.$arg,
  648.                                         CONSOLE_GETARGS_ERROR_USER, PEAR_ERROR_RETURN,
  649.                                         null, 'Console_Getargs_Options::parseArgs()');
  650.             }
  651.             if ($err !== true) {
  652.                 return $err;
  653.             }
  654.         }
  655.         // Check to see if we need to reload the arguments
  656.         // due to concatenated short names.
  657.         if (isset($err) && $err === -1) {
  658.             return $this->parseArgs();
  659.         }
  660.         
  661.         return true;
  662.     }
  663.     
  664.     /**
  665.      * Parses one option/argument
  666.      * @access private
  667.      * @throws CONSOLE_GETARGS_ERROR_USER
  668.      * @return true|PEAR_Error
  669.      */
  670.     function parseArg($arg, $isLong, &$pos)
  671.     {
  672.         // If the whole short option isn't in the shortLong array
  673.         // then break it into a bunch of switches.
  674.         if (!$isLong && !isset($this->_shortLong[$arg]) && strlen($arg) > 1) {
  675.             $newArgs = array();
  676.             for ($i = 0; $i < strlen($arg); $i++) {
  677.                 if (array_key_exists($arg{$i}, $this->_shortLong)) {
  678.                     $newArgs[] = '-' . $arg{$i};
  679.                 } else {
  680.                     $newArgs[] = $arg{$i};
  681.                 }
  682.             }
  683.             // Add the new args to the array.
  684.             array_splice($this->args, $pos, 1, $newArgs);
  685.             
  686.             // Reset the option values.
  687.             $this->_longLong = array();
  688.             
  689.             // Then reparse the arguments.
  690.             return -1;
  691.         }
  692.         
  693.         $opt = '';
  694.         for ($i = 0; $i < strlen($arg); $i++) {
  695.             // Build the option name one char at a time looking for a match.
  696.             $opt .= $arg{$i};
  697.             if ($isLong === false && isset($this->_shortLong[$opt])) {
  698.                 // Found a match in the short option names.
  699.                 $cmp = $opt;
  700.                 $long = $this->_shortLong[$opt];
  701.             } elseif ($isLong === true && isset($this->_config[$opt])) {
  702.                 // Found a match in the long option names.
  703.                 $long = $cmp = $opt;
  704.             } elseif ($isLong === true && isset($this->_aliasLong[$opt])) {
  705.                 // Found a match in the long option names.
  706.                 $long = $this->_aliasLong[$opt];
  707.                 $cmp = $opt;
  708.             }
  709.             if ($arg{$i} === '=') {
  710.                 // End of the option name when '=' is found.
  711.                 break;
  712.             }
  713.         }
  714.  
  715.         // If no option name is found, assume -- was passed.
  716.         if ($opt == '') {
  717.             $long = CONSOLE_GETARGS_PARAMS;
  718.         }
  719.         
  720.         if (isset($long)) {
  721.             // A match was found.
  722.             if (strlen($arg) > strlen($cmp)) {
  723.                 // Seperate the argument from the option.
  724.                 // Ex: php test.php -f=image.png
  725.                 //     $cmp = 'f'
  726.                 //     $arg = 'f=image.png'
  727.                 $arg = substr($arg, strlen($cmp));
  728.                 // Now $arg = '=image.png'
  729.                 if ($arg{0} === '=') {
  730.                     $arg = substr($arg, 1);
  731.                     // Now $arg = 'image.png'
  732.                 }
  733.             } else {
  734.                 // No argument passed for option.
  735.                 $arg = '';
  736.             }
  737.             // Set the options value.
  738.             return $this->setValue($long, $arg, $pos);
  739.         }
  740.         return PEAR::raiseError('Unknown argument '.$opt,
  741.                                 CONSOLE_GETARGS_ERROR_USER, PEAR_ERROR_RETURN,
  742.                                 null, 'Console_Getargs_Options::parseArg()');
  743.     }
  744.     
  745.     /**
  746.      * Set the option arguments
  747.      * @access private
  748.      * @throws CONSOLE_GETARGS_ERROR_CONFIG
  749.      * @throws CONSOLE_GETARGS_ERROR_USER
  750.      * @return true|PEAR_Error
  751.      */
  752.     function setValue($optname, $value, &$pos)
  753.     {
  754.         if (!isset($this->_config[$optname]['max'])) {
  755.             // Max must be set for every option even if it is zero or -1.
  756.             return PEAR::raiseError('No max parameter set for '.$optname,
  757.                                     CONSOLE_GETARGS_ERROR_CONFIG, PEAR_ERROR_TRIGGER,
  758.                                     E_USER_WARNING, 'Console_Getargs_Options::setValue()');
  759.         }
  760.         
  761.         $max = $this->_config[$optname]['max'];
  762.         $min = isset($this->_config[$optname]['min']) ? $this->_config[$optname]['min']: $max;
  763.         
  764.         // A value was passed after the option.
  765.         if ($value !== '') {
  766.             // Argument is like -v5
  767.             if ($min == 1 && $max > 0) {
  768.                 // At least one argument is required for option.
  769.                 $this->updateValue($optname, $value);
  770.                 return true;
  771.             }
  772.             if ($max === 0) {
  773.                 // Argument passed but not expected.
  774.                 return PEAR::raiseError('Argument '.$optname.' does not take any value',
  775.                                         CONSOLE_GETARGS_ERROR_USER, PEAR_ERROR_RETURN,
  776.                                         null, 'Console_Getargs_Options::setValue()');
  777.             }
  778.             // Not enough arguments passed for this option.
  779.             return PEAR::raiseError('Argument '.$optname.' expects more than one value',
  780.                                     CONSOLE_GETARGS_ERROR_USER, PEAR_ERROR_RETURN,
  781.                                     null, 'Console_Getargs_Options::setValue()');
  782.         }
  783.         
  784.         if ($min === 1 && $max === 1) {
  785.             // Argument requires 1 value
  786.             // If optname is "parameters" take a step back.
  787.             if ($optname == CONSOLE_GETARGS_PARAMS) {
  788.                 $pos--;
  789.             }
  790.             if (isset($this->args[$pos+1]) && $this->isValue($this->args[$pos+1])) {
  791.                 // Set the option value and increment the position.
  792.                 $this->updateValue($optname, $this->args[$pos+1]);
  793.                 $pos++;
  794.                 return true;
  795.             }
  796.             // What we thought was the argument was really the next option.
  797.             return PEAR::raiseError('Argument '.$optname.' expects one value',
  798.                                     CONSOLE_GETARGS_ERROR_USER, PEAR_ERROR_RETURN,
  799.                                     null, 'Console_Getargs_Options::setValue()');
  800.             
  801.         } else if ($max === 0) {
  802.             // Argument is a switch
  803.             if (isset($this->args[$pos+1]) && $this->isValue($this->args[$pos+1])) {
  804.                 // What we thought was the next option was really an argument for this option.
  805.                 // First update the value
  806.                 $this->updateValue($optname, true);                
  807.                 // Then try to assign values to parameters.
  808.                 if (isset($this->_config[CONSOLE_GETARGS_PARAMS])) {
  809.                     return $this->setValue(CONSOLE_GETARGS_PARAMS, '', ++$pos);
  810.                 } else {
  811.                     return PEAR::raiseError('Argument '.$optname.' does not take any value',
  812.                                             CONSOLE_GETARGS_ERROR_USER, PEAR_ERROR_RETURN,
  813.                                             null, 'Console_Getargs_Options::setValue()');
  814.                 }
  815.             }
  816.             // Set the switch to on.
  817.             $this->updateValue($optname, true);
  818.             return true;
  819.             
  820.         } else if ($max >= 1 && $min === 0) {
  821.             // Argument has a default-if-set value
  822.             if (!isset($this->_config[$optname]['default'])) {
  823.                 // A default value MUST be assigned when config is loaded.
  824.                 return PEAR::raiseError('No default value defined for '.$optname,
  825.                                         CONSOLE_GETARGS_ERROR_CONFIG, PEAR_ERROR_TRIGGER,
  826.                                         E_USER_WARNING, 'Console_Getargs_Options::setValue()');
  827.             }
  828.             if (is_array($this->_config[$optname]['default'])) {
  829.                 // Default value cannot be an array.
  830.                 return PEAR::raiseError('Default value for '.$optname.' must be scalar',
  831.                                         CONSOLE_GETARGS_ERROR_CONFIG, PEAR_ERROR_TRIGGER,
  832.                                         E_USER_WARNING, 'Console_Getargs_Options::setValue()');
  833.             }
  834.             
  835.             // If optname is "parameters" take a step back.
  836.             if ($optname == CONSOLE_GETARGS_PARAMS) {
  837.                 $pos--;
  838.             }
  839.             
  840.             if (isset($this->args[$pos+1]) && $this->isValue($this->args[$pos+1])) {
  841.                 // Assign the option the value from the command line if there is one.
  842.                 $this->updateValue($optname, $this->args[$pos+1]);
  843.                 $pos++;
  844.                 return true;
  845.             }
  846.             // Otherwise use the default value.
  847.             $this->updateValue($optname, $this->_config[$optname]['default']);
  848.             return true;
  849.         }
  850.         
  851.         // Argument takes one or more values
  852.         $added = 0;
  853.         // If trying to assign values to parameters, must go back one position.
  854.         if ($optname == CONSOLE_GETARGS_PARAMS) {
  855.             $pos = max($pos - 1, -1);
  856.         }
  857.         for ($i = $pos + 1; $i <= count($this->args); $i++) {
  858.             $paramFull = $max <= count($this->getValue($optname)) && $max != -1;
  859.             if (isset($this->args[$i]) && $this->isValue($this->args[$i]) && !$paramFull) {
  860.                 // Add the argument value until the next option is hit.
  861.                 $this->updateValue($optname, $this->args[$i]);
  862.                 $added++;
  863.                 $pos++;
  864.                 // Only keep trying if we haven't filled up yet.
  865.                 // or there is no limit
  866.                 if (($added < $max || $max < 0) && ($max < 0 || !$paramFull)) {
  867.                     continue;
  868.                 }
  869.             }
  870.             if ($min > $added && !$paramFull) {
  871.                 // There aren't enough arguments for this option.
  872.                 return PEAR::raiseError('Argument '.$optname.' expects at least '.$min.(($min > 1) ? ' values' : ' value'),
  873.                                         CONSOLE_GETARGS_ERROR_USER, PEAR_ERROR_RETURN,
  874.                                         null, 'Console_Getargs_Options::setValue()');
  875.             } elseif ($max !== -1 && $paramFull) {
  876.                 // Too many arguments for this option.
  877.                 // Try to add the extra options to parameters.
  878.                 if (isset($this->_config[CONSOLE_GETARGS_PARAMS]) && $optname != CONSOLE_GETARGS_PARAMS) {
  879.                     return $this->setValue(CONSOLE_GETARGS_PARAMS, '', ++$pos);
  880.                 } elseif ($optname == CONSOLE_GETARGS_PARAMS && empty($this->args[$i])) {
  881.                     $pos += $added;
  882.                     break;
  883.                 } else {
  884.                     return PEAR::raiseError('Argument '.$optname.' expects maximum '.$max.' values',
  885.                                             CONSOLE_GETARGS_ERROR_USER, PEAR_ERROR_RETURN,
  886.                                             null, 'Console_Getargs_Options::setValue()');
  887.                 }
  888.             }
  889.             break;
  890.         }
  891.         // Everything went well.
  892.         return true;
  893.     }
  894.     
  895.     /**
  896.      * Checks whether the given parameter is an argument or an option
  897.      * @access private
  898.      * @return boolean
  899.      */
  900.     function isValue($arg)
  901.     {
  902.         if ((strlen($arg) > 1 && $arg{0} == '-' && $arg{1} == '-') ||
  903.             (strlen($arg) > 1 && $arg{0} == '-')) {
  904.             // The next argument is really an option.
  905.             return false;
  906.         }
  907.         return true;
  908.     }
  909.     
  910.     /**
  911.      * Adds the argument to the option
  912.      *
  913.      * If the argument for the option is already set,
  914.      * the option arguments will be changed to an array
  915.      * @access private
  916.      * @return void
  917.      */
  918.     function updateValue($optname, $value)
  919.     {
  920.         if (isset($this->_longLong[$optname])) {
  921.             if (is_array($this->_longLong[$optname])) {
  922.                 // Add this value to the list of values for this option.
  923.                 $this->_longLong[$optname][] = $value;
  924.             } else {
  925.                 // There is already one value set. Turn everything into a list of values.
  926.                 $prevValue = $this->_longLong[$optname];
  927.                 $this->_longLong[$optname] = array($prevValue);
  928.                 $this->_longLong[$optname][] = $value;
  929.             }
  930.         } else {
  931.             // This is the first value for this option.
  932.             $this->_longLong[$optname] = $value;
  933.         }
  934.     }
  935.     
  936.     /**
  937.      * Sets the option default arguments when necessary
  938.      * @access private
  939.      * @return true
  940.      */
  941.     function setDefaults()
  942.     {
  943.         foreach ($this->_config as $longname => $def) {
  944.             // Add the default value only if the default is defined 
  945.             // and the option requires at least one argument.
  946.             if (isset($def['default']) && 
  947.                 ((isset($def['min']) && $def['min'] !== 0) ||
  948.                 (!isset($def['min']) & isset($def['max']) && $def['max'] !== 0)) &&
  949.                 !isset($this->_longLong[$longname])) {
  950.                 $this->_longLong[$longname] = $def['default'];
  951.             }
  952.         }
  953.         return true;
  954.     }
  955.     
  956.     /**
  957.      * Checks whether the given option is defined
  958.      *
  959.      * An option will be defined if an argument was assigned to it using
  960.      * the command line options. You can use the short, the long or
  961.      * an alias name as parameter.
  962.      *
  963.      * @access public
  964.      * @param  string the name of the option to be checked
  965.      * @return boolean true if the option is defined
  966.      */
  967.     function isDefined($optname)
  968.     {
  969.         $longname = $this->getLongName($optname);
  970.         if (isset($this->_longLong[$longname])) {
  971.             return true;
  972.         }
  973.         return false;
  974.     }
  975.     
  976.     /**
  977.      * Returns the long version of the given parameter
  978.      *
  979.      * If the given name is not found, it will return the name that
  980.      * was given, without further ensuring that the option
  981.      * actually exists
  982.      *
  983.      * @access private
  984.      * @param  string the name of the option
  985.      * @return string long version of the option name
  986.      */
  987.     function getLongName($optname)
  988.     {
  989.         if (isset($this->_shortLong[$optname])) {
  990.             // Short version was passed.
  991.             $longname = $this->_shortLong[$optname];
  992.         } else if (isset($this->_aliasLong[$optname])) {
  993.             // An alias was passed.
  994.             $longname = $this->_aliasLong[$optname];
  995.         } else {
  996.             // No further validation is done.
  997.             $longname = $optname;
  998.         }
  999.         return $longname;
  1000.     }
  1001.     
  1002.     /**
  1003.      * Returns the argument of the given option
  1004.      *
  1005.      * You can use the short, alias or long version of the option name.
  1006.      * This method will try to find the argument(s) of the given option name.
  1007.      * If it is not found it will return null. If the arg has more than
  1008.      * one argument, an array of arguments will be returned.
  1009.      *
  1010.      * @access public
  1011.      * @param  string the name of the option
  1012.      * @return array|string|null argument(s) associated with the option
  1013.      */
  1014.     function getValue($optname)
  1015.     {
  1016.         if ($this->isDefined($optname)) {
  1017.             // Option is defined. Return its value
  1018.             $longname = $this->getLongName($optname);
  1019.             return $this->_longLong[$longname];
  1020.         }
  1021.         // Option is not defined.
  1022.         return null;
  1023.     }
  1024.  
  1025.     /**
  1026.      * Returns all arguments that have been parsed and recognized
  1027.      *
  1028.      * The name of the options are stored in the keys of the array.
  1029.      * You may choose whether you want to use the long or the short
  1030.      * option names
  1031.      *
  1032.      * @access public
  1033.      * @param  string   option names to use for the keys (long or short)
  1034.      * @return array    values for all options
  1035.      */
  1036.     function getValues($optionNames = 'long')
  1037.     {
  1038.         switch ($optionNames) {
  1039.             case 'short':
  1040.                 $values = array();
  1041.                 foreach ($this->_shortLong as $short => $long) {
  1042.                     if (isset($this->_longLong[$long])) {
  1043.                         $values[$short] = $this->_longLong[$long];
  1044.                     }
  1045.                 }
  1046.                 if (isset($this->_longLong['parameters'])) {
  1047.                     $values['parameters'] = $this->_longLong['parameters'];
  1048.                 }
  1049.                 return $values;
  1050.             case 'long':
  1051.             default:
  1052.                 return $this->_longLong;
  1053.         }
  1054.     }
  1055. } // end class Console_Getargs_Options
  1056. /*
  1057.  * Local variables:
  1058.  * tab-width: 4
  1059.  * c-basic-offset: 4
  1060.  * End:
  1061.  */
  1062. ?>